package com.liang.maogouyuyin.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.liang.maogouyuyin.R;
import com.liang.maogouyuyin.TheBaseApplication;
import com.liang.maogouyuyin.bean.AnomalyBean;
import com.liang.maogouyuyin.bean.CasebookBean;
import com.liang.maogouyuyin.bean.ExpenditureBean;
import com.liang.maogouyuyin.bean.WeightBean;
import com.liang.maogouyuyin.databinding.FragmentRecordBinding;
import com.liang.maogouyuyin.local.LocalRepository;
import com.liang.maogouyuyin.ui.activity.AddDetailActivity;
import com.liang.maogouyuyin.ui.activity.AddPetActivity;
import com.liang.maogouyuyin.ui.activity.RecordDetailActivity;
import com.liang.maogouyuyin.ui.viewmodel.AnomalyViewModel;
import com.liang.maogouyuyin.ui.viewmodel.CasebookViewModel;
import com.liang.maogouyuyin.ui.viewmodel.ExpenditureViewModel;
import com.liang.maogouyuyin.ui.viewmodel.PetViewModel;
import com.liang.maogouyuyin.ui.viewmodel.WeightViewModel;
import com.liang.maogouyuyin.utils.DateUtil;
import com.liang.maogouyuyin.widget.popup.SelectPetPopup;
import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;

import java.io.File;

public class RecordFragment extends Fragment {
    FragmentRecordBinding binding;
    @SuppressLint("StaticFieldLeak")
    public static FrameLayout mFeedContainer;

    private PetViewModel petViewModel;
    private ExpenditureViewModel expenditureViewModel;
    private WeightViewModel weightViewModel;
    private AnomalyViewModel anomalyViewModel;
    private CasebookViewModel casebookViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentRecordBinding.inflate(inflater,container,false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initData();
        initClick();
        updateUI();
    }

    @Override
    public void onResume() {
        super.onResume();
        String petName = LocalRepository.INSTANCE.getCurrentPet();
        petViewModel.loadAll();
        if (!petName.isEmpty()) {
            loadData(petName);
        }
    }

    private void initData() {
        petViewModel = TheBaseApplication.getInstance().getPetViewModel();
        petViewModel.loadAll();

        expenditureViewModel = TheBaseApplication.getInstance().getExpenditureViewModel();

        weightViewModel = TheBaseApplication.getInstance().getWeightViewModel();

        anomalyViewModel = TheBaseApplication.getInstance().getAnomalyViewModel();

        casebookViewModel = TheBaseApplication.getInstance().getCasebookViewModel();
    }

    private void initClick() {
        binding.recordAddPet.setOnClickListener(view -> {
            startActivity(new Intent(requireContext(), AddPetActivity.class));
        });

        binding.itemPetProfilePhoto.setOnClickListener(view -> {
            if (!checkHasPet()) {
                startActivity(new Intent(requireContext(), AddPetActivity.class));
            }
        });

        binding.recordPetSwitch.setOnClickListener(view -> {
            if (checkHasPet()) {
                new XPopup.Builder(requireContext())
                        .asCustom(new SelectPetPopup(requireContext())
                                .setList(petViewModel.getPetList().getValue())
                                .setListener((petName) -> {
                                    loadData(petName);
                                })
                        ).show();
            }
        });

        binding.recordBill.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(0);
        });

        binding.recordBillDetail.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(0);
        });

        binding.recordBillAdd.setOnClickListener(view -> {
            if (checkHasPet())
                startAddDetailActivity(0);
        });

        binding.recordWeight.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(1);
        });

        binding.recordWeightDetail.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(1);
        });

        binding.recordWeightAdd.setOnClickListener(view -> {
            if (checkHasPet())
                startAddDetailActivity(1);
        });

        binding.recordAnomaly.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(2);
        });

        binding.recordAnomalyDetail.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(2);
        });

        binding.recordAnomalyAdd.setOnClickListener(view -> {
            if (checkHasPet())
                startAddDetailActivity(2);
        });

        binding.recordCasebook.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(3);
        });

        binding.recordCasebookDetail.setOnClickListener(view -> {
            if (checkHasPet())
                startRecordDetailActivity(3);
        });

        binding.recordCasebookAdd.setOnClickListener(view -> {
            if (checkHasPet())
                startAddDetailActivity(3);
        });
    }

    @SuppressLint("SetTextI18n")
    private void updateUI() {
        petViewModel.getPet().observe(getViewLifecycleOwner(), petBean -> {
            Glide.with(requireActivity()).load(new File(petBean.getProfile())).into(binding.itemPetProfilePhoto);
            binding.itemPetName.setText(petBean.getName());
            binding.itemPetAge.setText(String.format(getString(R.string.record_default_format_pet_age), DateUtil.INSTANCE.getAge(petBean.getBirthday())));
            binding.itemPetAccompany.setText(String.format(getString(R.string.record_default_format_pet_accompany), DateUtil.INSTANCE.getDays(petBean.getArriveHome())));
        });

        expenditureViewModel.getExpenditureList().observe(getViewLifecycleOwner(), expenditureBeans -> {
            if (!expenditureBeans.isEmpty()) {
                ExpenditureBean bean = expenditureBeans.get(0);
                binding.recordBillDetailDate.setText(DateUtil.INSTANCE.formatTimeStamp(bean.getDate(), "日期：yyyy-M-d"));
                binding.recordBillDetailExpenditure.setText("支出：" + String.format(getString(R.string.record_detail_bill_sum), bean.getMoney()));
                binding.recordBillDetailContent.setText("备注：" + bean.getContent());
                float sum = 0;
                for (int i = 0; i < expenditureBeans.size(); i++) {
                    sum += expenditureBeans.get(i).getMoney();
                }
                binding.recordBillText.setText(String.format(getString(R.string.record_detail_bill_sum), sum));
            } else {
                binding.recordBillDetailDate.setText("");
                binding.recordBillDetailExpenditure.setText("");
                binding.recordBillDetailContent.setText("");
                binding.recordBillText.setText("");
            }
        });

        weightViewModel.getWeightList().observe(getViewLifecycleOwner(), weightBeans -> {
            if (!weightBeans.isEmpty()) {
                WeightBean bean = weightBeans.get(0);
                binding.recordWeightDetailDate.setText(DateUtil.INSTANCE.formatTimeStamp(bean.getDate(), "日期：yyyy-M-d"));
                binding.recordWeightDetailWeight.setText("体重：" + String.format(getString(R.string.record_detail_weight_sum), bean.getWeight()));
                binding.recordWeightText.setText(String.format(getString(R.string.record_detail_weight_sum), bean.getWeight()));
            } else {
                binding.recordWeightDetailDate.setText("");
                binding.recordWeightDetailWeight.setText("");
                binding.recordWeightText.setText("");
            }
        });

        anomalyViewModel.getAnomalyList().observe(getViewLifecycleOwner(), anomalyBeans -> {
            if (!anomalyBeans.isEmpty()) {
                AnomalyBean bean = anomalyBeans.get(0);
                binding.recordAnomalyDetailDate.setText(DateUtil.INSTANCE.formatTimeStamp(bean.getDate(), "日期：yyyy-M-d"));
                binding.recordAnomalyDetailAnomaly.setText("异常：" + bean.getAnomalyName());
                binding.recordAnomalyText.setText(String.valueOf(anomalyBeans.size()));
            } else {
                binding.recordAnomalyDetailDate.setText("");
                binding.recordAnomalyDetailAnomaly.setText("");
                binding.recordAnomalyText.setText("");
            }
        });

        casebookViewModel.getCasebookList().observe(getViewLifecycleOwner(), casebookBeans -> {
            if (!casebookBeans.isEmpty()) {
                CasebookBean bean = casebookBeans.get(0);
                binding.recordCasebookDetailDate.setText(DateUtil.INSTANCE.formatTimeStamp(bean.getDate(), "日期：yyyy-M-d"));
                binding.recordCasebookDetailHospital.setText("医院：" + bean.getHospital());
                binding.recordCasebookDetailCasebook.setText("病症：" + bean.getCasebook());
                binding.recordCasebookDetailContent.setText("备注：" + bean.getContent());
                binding.recordCasebookText.setText(String.valueOf(casebookBeans.size()));
            } else {
                binding.recordCasebookDetailDate.setText("");
                binding.recordCasebookDetailHospital.setText("");
                binding.recordCasebookDetailCasebook.setText("");
                binding.recordCasebookDetailContent.setText("");
                binding.recordCasebookText.setText("");
            }
        });
    }

    private void startRecordDetailActivity(int type) {
        Intent intent = new Intent(requireContext(), RecordDetailActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    private void startAddDetailActivity(int type) {
        Intent intent = new Intent(requireContext(), AddDetailActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    private boolean checkHasPet() {
        if (LocalRepository.INSTANCE.getCurrentPet().isEmpty()) {
            Toast.makeText(requireContext(), "还没有宠物，快去添加吧！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void loadData(String petName) {
        petViewModel.loadPetByName(petName);
        expenditureViewModel.loadExpenditureByName(petName);
        weightViewModel.loadWeightByName(petName);
        anomalyViewModel.loadAnomalyByName(petName);
        casebookViewModel.loadCasebookByName(petName);
    }
}
